package cn.dataling.ai.component;

import cn.dataling.ai.common.ExceptionCore;
import cn.dataling.ai.common.ResponseStatusCodeEnum;
import cn.dataling.ai.model.XcxLoginDTO;
import cn.dataling.ai.model.XcxLoginResp;
import cn.dataling.ai.model.XcxLoginVO;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class XcxComponent {

    private static final Logger LOGGER = LoggerFactory.getLogger(XcxComponent.class);

    @Value("${xcx.authUrl}")
    private String authUrlTemplate;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private JacksonComponent jacksonComponent;

    private static final Map<String, Boolean> LOGIN = new ConcurrentHashMap<>();


    public XcxLoginVO xcxLogin(XcxLoginDTO data) {
        XcxLoginVO xcxLoginVO = new XcxLoginVO();
        XcxLoginResp xcxLoginResp = openId(data.getCode());
        xcxLoginVO.setOpenId(xcxLoginResp.getOpenid());

        LOGIN.put(xcxLoginResp.getOpenid(), true);

        return xcxLoginVO;
    }

    public XcxLoginResp openId(String code) {
        String authUrl = String.format(authUrlTemplate, code);
        String forObject = restTemplate.getForObject(authUrl, String.class);
        XcxLoginResp xcxLoginResp = jacksonComponent.fromJson(forObject, XcxLoginResp.class);
        if (ObjectUtils.isEmpty(xcxLoginResp) || !ObjectUtils.isEmpty(xcxLoginResp.getErrcode())) {
            LOGGER.warn("xcx openId info is {}", xcxLoginResp);
            throw new ExceptionCore(ResponseStatusCodeEnum.OPEN_ID_GET_FAIL);
        }
        return xcxLoginResp;
    }

    public Boolean isLogin(String openId) {
        return LOGIN.getOrDefault(openId, false);
    }

}
